﻿using System;
using System.Text;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace Bpms.Common
{
    /// <summary>
    /// 通用函数类
    /// </summary>
    public class Utility
    {
        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns>字符长度</returns>
        public static int GetStringLength(string stringValue)
        {
            return Encoding.Default.GetBytes(stringValue).Length;
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }

                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        #region --- byte数组与十六进制字符串转换 ---

        /// <summary>
        /// 将byte数组转换成十六进制字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string BytesToHexString(byte[] data)
        {
            int iCnt = data.GetLength(0);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < iCnt; i++)
            {
                sb.AppendFormat("{0:X2}", data[i]);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 将十六进制字符串转换成byte数组
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(string hex)
        {
            // hex串长为奇数或hex为空串
            if (null == hex)
                return null;
            if (hex.Length % 2 != 0 || 0 == hex.Length)
            {
                return null;
            }

            byte[] ret = new byte[hex.Length / 2];
            ret.Initialize();
            for (int n = 0; n < ret.Length; n++)
            {
                try
                {
                    ret[n] = byte.Parse(hex.Substring(n * 2, 2), NumberStyles.AllowHexSpecifier);
                }
                catch (Exception ee)
                {
                    string err = ee.Message;
                    return null;
                }
            }
            return ret;
        }
        #endregion

        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <param name="recordCount">记录数</param>
        /// <param name="pageSize">每页个数</param>
        public static int GetPageCount(int recordCount, int pageSize)
        {
            return recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
        }

        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {

                return "";
            }
            return HttpContext.Current.Request.QueryString[strName];
        }

        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.Form[strName];
        }

        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static int GetQueryInt(string strName)
        {
            return ToInt(HttpContext.Current.Request.QueryString[strName]);
        }

        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content">content(string)</param>
        /// <returns>string</returns>
        public static string RemoveHtml(string content)
        {
            string regexstr = @"<[^>]*>";

            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (null == result || result == String.Empty || !Validity.IsValidIP(result))
            {
                return "0.0.0.0";
            }

            return result;
        }

        /// <summary>
        /// 截取字符串，过长加"..."
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="isUseTitle">是否需要鼠标悬停时全部显示</param>
        /// <returns></returns>
        public static string CutString(string str, int length, bool isUseTitle)
        {
            if (str.Length > length)
            {
                if (isUseTitle == true)
                {
                    return "<span title='" + str + "' >" + str.Substring(0, length) + "...</span>";
                }
                else
                {
                    return str.Substring(0, length) + "...";
                }
            }
            else
            {
                if (isUseTitle == true)
                {
                    return "<span title='" + str + "' >" + str + "</span>";
                }

                return str;
            }
        }

        /// <summary>
        /// 获得来源URL
        /// </summary>
        public static string Referrer
        {
            get
            {
                Uri uri = HttpContext.Current.Request.UrlReferrer;
                if (uri == null)
                {
                    return string.Empty;
                }

                return Convert.ToString(uri);
            }
        }

        #region Convert

        /// <summary>
        /// 转换为DateTime
        /// </summary>
        /// <param name="obj">object</param>
        /// <returns>DateTime</returns>
        public static DateTime ToDateTime(object obj)
        {
            if ((obj != DBNull.Value) && (obj != null))
            {
                return Convert.ToDateTime(obj.ToString());
            }
            else
            {
                return DateTime.Now;
            }
        }

        /// <summary>
        /// 转换为string（默认值为空）
        /// </summary>
        /// <param name="obj">object</param>
        /// <returns>string</returns>
        public static string ToString(object obj)
        {
            if ((obj != DBNull.Value) && (obj != null))
            {
                return obj.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// 转换为string（可设定默认值）
        /// </summary>
        /// <param name="obj">object</param>
        /// <param name="defValue">default value(string)</param>
        /// <returns>string</returns>
        public static string ToString(object obj, string defValue)
        {
            if ((obj != DBNull.Value) && (obj != null))
            {
                return obj.ToString();
            }
            else
            {
                return defValue;
            }
        }

        /// <summary>
        /// 转换为string array
        /// </summary>
        /// <param name="coll">StringCollection</param>
        /// <returns>string[]</returns>
        public static string[] ToStringArray(StringCollection coll)
        {
            String[] strReturn = new String[coll.Count];
            coll.CopyTo(strReturn, 0);

            return strReturn;
        }

        /// <summary>
        /// 转换为bool
        /// </summary>
        /// <param name="obj">object</param>
        /// <returns>bool</returns>
        public static bool ToBool(object obj)
        {
            if ((obj != DBNull.Value) && (obj != null))
            {
                return Convert.ToBoolean(obj);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 转换为 int（默认值为0）
        /// </summary>
        /// <param name="obj">object</param>
        /// <returns>int</returns>
        public static int ToInt(object obj)
        {
            int value = 0;
            if ((obj != DBNull.Value) && (obj != null))
            {
                int.TryParse(obj.ToString(), out value);
            }

            return value;
        }

        /// <summary>
        /// 转换为 int（可设置默认值）
        /// </summary>
        /// <param name="obj">object</param>
        /// <param name="defValue">default value(int)</param>
        /// <returns>int</returns>
        public static int ToInt(object obj, int defValue)
        {
            int value = defValue;
            if ((obj != DBNull.Value) && (obj != null))
            {
                int.TryParse(obj.ToString(), out value);
            }

            return value;
        }

        /// <summary>
        /// 转换为currency string
        /// </summary>
        /// <param name="f">float</param>
        /// <returns>string</returns>
        public static string ToCurrency(float f)
        {
            return string.Format("{0:C2}", f);
        }

        /// <summary>
        /// 保留两位小数
        /// </summary>
        /// <param name="f">float</param>
        /// <returns>e.g. (121.12)</returns>
        public static string ToF2(float f)
        {
            return string.Format("{0:F2}", f);
        }

        #endregion

        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string strInput)
        {
            return Regex.IsMatch(strInput, @"[\u4e00-\u9fa5]");
        }

        #region Cookie
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        public static void WriteCookie(string name, string value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie == null)
            {
                cookie = new HttpCookie(name);
            }
            cookie.Value = value;

            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void WriteCookie(string name, string key, string value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie == null)
            {
                cookie = new HttpCookie(name);
            }
            cookie[key] = value;

            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        /// <param name="expires">过期时间(分钟)</param>
        public static void WriteCookie(string name, string value, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie == null)
            {
                cookie = new HttpCookie(name);
            }
            cookie.Value = value;
            cookie.Expires = DateTime.Now.AddMinutes(expires);

            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string name)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[name] != null)
            {
                return HttpContext.Current.Request.Cookies[name].Value.ToString();
            }

            return "";
        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string name, string key)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[name] != null && HttpContext.Current.Request.Cookies[name][key] != null)
            {
                return HttpContext.Current.Request.Cookies[name][key].ToString();
            }

            return "";
        }
        #endregion
    }
}
